//
//  LocationUtils.swift
//  puretennis
//
//  Created by Derek Zheng on 12/18/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import Foundation
import CoreLocation

class LocationManager: NSObject {
    var manager: OneShotLocationManager?
    
    func updateMyLocation(){
        self.manager = OneShotLocationManager()
        
        manager!.fetchWithCompletion {location, error in
            if let loc = location {
                CLGeocoder().reverseGeocodeLocation(loc, completionHandler: { (placemarkers, errors) -> Void in
                    if(placemarkers != nil && placemarkers.count > 0){
                        let pm = placemarkers[0] as CLPlacemark
                        self.doUpdateMyLocation(pm)
                    }
                })
            } else if let err = error {
                Utils.debug(err.localizedDescription)
            }
            
            self.manager = nil;
        }
    }
    
    func doUpdateMyLocation(placemark: CLPlacemark){
        var city = placemark.locality as String;
        var coordinate = placemark.location.coordinate
        var latitude = coordinate.latitude;
        var longitude = coordinate.longitude;
        var currentLocation = NSMutableDictionary()
        currentLocation.setValue(city, forKey: "city")
        currentLocation.setValue(String(format:"%f", latitude), forKey: "latitude")
        currentLocation.setValue(String(format:"%f", longitude), forKey: "longitude")
        
        var url = "/api/v1/user/updatelocation"
        
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: currentLocation, successHandle: { (response) -> Void in
            self.cacheLocation(response);
            }, errorHandle: { (error) -> Void in
                
        });
    }
    
    func cacheLocation(response:AnyObject?){
        Utils.saveData(response as NSDictionary, key: "currentLocation");
    }
    
    class func toDouble(value: String) -> Double? {
        return NSNumberFormatter().numberFromString(value)?.doubleValue
    }
    
    
    class func toLocation(location: NSDictionary) -> CLLocation{
        
        var latitude = location.objectForKey("latitude") as String
        if(latitude.isEmpty){
            latitude = "0"
        }
        var longitude = location.objectForKey("longitude") as String
        if(longitude.isEmpty){
            longitude = "0"
        }
        
        var latAsDouble = self.toDouble(latitude)!
        var longiAsDouble = self.toDouble(longitude)!
        return CLLocation(latitude: latAsDouble, longitude: longiAsDouble)
    }
    
    class func toDistanceText(distance: Double) -> String{
        var distanceAsInt = Int(distance)
        
        if(distanceAsInt >= 1000){
            return "\(distanceAsInt/1000)公里"
        }else{
            return "\(distanceAsInt)米"
        }
    }
    
}